import {defineStore} from "pinia"
import type {LoginSubmitResponsePermissionTreeDTOListType} from "@/types/loginType.ts";
import {getTreeItem} from "@/utils";
import Local from "@/utils/local";

const useLayoutStore = defineStore('layout', {
    state: (): {
        width: number
        collapsedWidth: number
        collapsed: boolean
        list: LoginSubmitResponsePermissionTreeDTOListType[]
        tabList: {
            name: string
            url: string
            closable: boolean
        }[]
    } => ({
        width: 200,
        collapsedWidth: 48,
        collapsed: false,
        list: [],
        tabList: []
    }),
    actions: {
        getWidth() {
            return this.width
        },
        getCollapsedWidth() {
            return this.collapsedWidth
        },
        getCollapsed() {
            return this.collapsed
        },
        setCollapsed(bool: boolean) {
            this.collapsed = bool
        },
        setList(list: LoginSubmitResponsePermissionTreeDTOListType[]) {
            this.list = list
        },
        getList() {
            return this.list
        },
        setTabList(url: string, key: keyof LoginSubmitResponsePermissionTreeDTOListType = 'url') {
            const row = getTreeItem<LoginSubmitResponsePermissionTreeDTOListType, string>(this.list, url, key, 'children')

            if (row) {
                const find = this.tabList.find(item => item.url === row.url)
                // 查询不到添加上去

                if (!find) {
                    this.tabList.push({
                        name: row!.name,
                        url: row!.url,
                        closable: true,
                    })
                    Local.SessSave('tabs', JSON.stringify(this.tabList))
                }
            }
        },
        deleteTabList(i: number) {
            this.tabList.splice(i, 1)
            Local.SessSave('tabs', JSON.stringify(this.tabList))
        },
        setTabs() {
            this.tabList = JSON.parse(Local.SessRead('tabs') || '[]')
        },
        clearTabList() {
            this.tabList = []
        },
        getTabList() {
            return this.tabs
        }
    },
    getters: {
        logoWidth: (state) => {
            return {
                width: `${state.width}px`,
            }
        },
        tabs: (state) => {
            const route = Local.localRead('defaultRouter')
            return state.tabList.map(item => {
                if (route === item.url) {
                    return {
                        ...item,
                        closable: false
                    }
                }
                return {
                    ...item
                }
            })
        }
    }
})


export default useLayoutStore